<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>Testing Actions</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="guides.html">Guides</a>&nbsp;&gt;&nbsp;<a href="plugin-developers-guide.html">Plugin Developers Guide</a>&nbsp;&gt;&nbsp;<a href="junit-plugin.html">JUnit Plugin</a>&nbsp;&gt;&nbsp;<a href="testing-actions.html">Testing Actions</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">Testing Actions</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=2330106">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=2330106">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=2330106">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=2330106">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=2330106">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=2330106">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><p>The recommended way to test actions is to instantiate the action classes and test them. The <a shape="rect" href="junit-plugin.html">JUnit Plugin</a> supports testing actions within a Struts invocation, meaning that a full request is simulated, and the output of the action can be tested. </p>

<h3 id="TestingActions-Strutsactions(withoutSpring)">Struts actions (without Spring)</h3>
<p>To test actions that do not use Spring, extend <code>StrutsTestCase</code>. The following example shows different ways of testing an action:<br clear="none">
Mapping:</p>
<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">
&lt;struts&gt;
    &lt;constant name="struts.objectFactory" value="spring"/&gt;
    &lt;package name="test" namespace="/test" extends="struts-default"&gt;
        &lt;action name="testAction" class="org.apache.struts2.TestAction"&gt;
            &lt;result type="freemarker"&gt;/template.ftl&lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;
</pre>
</div></div>
<p>Action:</p>
<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">
public class TestAction extends ActionSupport {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</pre>
</div></div>
<p>JUnit:</p>
<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">
package org.apache.struts2;

import org.apache.struts2.dispatcher.mapper.ActionMapping;

import java.util.HashMap;
import java.io.UnsupportedEncodingException;

import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.Action;

import javax.servlet.ServletException;

public class StrutsTestCaseTest extends StrutsTestCase {
    public void testGetActionMapping() {
        ActionMapping mapping = getActionMapping("/test/testAction.action");
        assertNotNull(mapping);
        assertEquals("/test", mapping.getNamespace());
        assertEquals("testAction", mapping.getName());
    }

    public void testGetActionProxy() throws Exception {
        //set parameters before calling getActionProxy
        request.setParameter("name", "FD");
        
        ActionProxy proxy = getActionProxy("/test/testAction.action");
        assertNotNull(proxy);

        TestAction action = (TestAction) proxy.getAction();
        assertNotNull(action);

        String result = proxy.execute();
        assertEquals(Action.SUCCESS, result);
        assertEquals("FD", action.getName());
    }

    public void testExecuteAction() throws ServletException, UnsupportedEncodingException {
        String output = executeAction("/test/testAction.action");
        assertEquals("Hello", output);
    }

    public void testGetValueFromStack() throws ServletException, UnsupportedEncodingException {
        request.setParameter("name", "FD");
        executeAction("/test/testAction.action");
        String name = (String) findValueAfterExecute("name");
        assertEquals("FD", name);
    }
}
</pre>
</div></div>

<h3 id="TestingActions-Thetemplate">The template</h3>
<p>If you use JSPs as the template engine you won't be able to test the action output outside the container. The <a shape="rect" href="embedded-jsp-plugin.html">Embedded JSP Plugin</a> can be used to overcome this limitation and be able to use JSPs from the classpath and outside the container.</p>

<p>There are several utility methods and mock objects defined in StrutsTestCase which can be used to facilitate the testing:<br clear="none">
Methods:</p>
<div class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Method Name</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>executeAction(String)</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Pass the url for the action, and it will return the output of the action. This output <strong>is not</strong> the action result, like "success", but what would be written to the result stream. To use this the actions must be using a result type that can be read from the classpath, like FreeMarker, velocity, etc (if you are using the experimental Embedded JSP Plugin, you can use JSPs also)</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>getActionProxy(String)</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Builds an action proxy that can be used to invoke an action, by calling <code>execute()</code> on the returned proxy object. The return value of <code>execute()</code> is the action result, like "success"</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>getActionMapping(String)</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Gets an <code>ActionMapping</code> for the url</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>injectStrutsDependencies(object)</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Injects Struts dependencies into an object (dependencies are marked with <code>Inject</code>)</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>findValueAfterExecute(String)</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Finds an object in the value stack, after an action has been executed</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>applyAdditionalParams(ActionContext)</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Can be overwritten in subclass to provide additional params and settings used during action invocation</p></td></tr></tbody></table></div>


<div class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Field</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>MockHttpServletRequest request</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>The request that will be passed to Struts. Make sure to set parameters in this object before calling methods like <code>getActionProxy</code></p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>MockHttpServletResponse response</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>The response object passed to Struts, you can use this class to test the output, response headers, etc</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>MockServletContext servletContext</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>The servlet context object passed to Struts</p></td></tr></tbody></table></div>


<h3 id="TestingActions-StrutsActionsusingSpring">Struts Actions using Spring</h3>
<p>Make sure to add a dependency to the <a shape="rect" href="spring-plugin.html">Spring Plugin</a> to your <code>pom.xml</code>:</p>
<div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">
&lt;dependency&gt;
    &lt;groupId&gt;org.apache.struts&lt;/groupId&gt;
    &lt;artifactId&gt;struts2-spring-plugin&lt;/artifactId&gt;
    &lt;version&gt;STRUTS_VERSION&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</div></div>

<p>If you use Spring as the object factory, the <code>StrutsSpringTestCase</code> class can be used to write your JUnits. This class extends <code>StrutsTestCase</code> and has a <code>applicationContext</code> field of type <code>ApplicationContext</code>. </p>

<p>The Spring context is loaded from "classpath*:applicationContext.xml" by default. To provide a different location, overwrite <code>getContextLocations</code>. </p></div>
        </div>

        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
